package com.solarsmile.gallery.viewmodel

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.solarsmile.gallery.model.PhotoItem
import com.solarsmile.gallery.model.Pixabay
import com.solarsmile.gallery.util.VolleySingleton
import kotlin.math.ceil

const val DATA_STATUS_LOAD_MORE = 0
const val DATA_STATUS_NO_MORE = 1
const val NET_WORK_ERROR = 2

class GalleryViewModel(application: Application) : AndroidViewModel(application) {
    private val _dataStatus = MutableLiveData<Int>()
    val dataStatus: LiveData<Int> get() = _dataStatus
    private val _gallery = MutableLiveData<List<PhotoItem>>()
    val gallery: LiveData<List<PhotoItem>> get() = _gallery
    private val keyWords = arrayOf("cat", "panda", "dog", "car", "bird", "sunshine", "computer")
    var scrollToTop = true
    private val perPage = 50
    private var currentPage = 1
    private var totalPage = 1
    var currentKey = ""
    private var isLoadMore = true
    private var isLoading = false

    init {
        loadMore()
    }

    fun loadMore(stringkey: String) {
        currentPage = 1
        totalPage = 1
        currentKey = stringkey
        isLoadMore = true
        scrollToTop = true
        fetchData()
    }

    fun loadMore() {
        currentPage = 1
        totalPage = 1
        currentKey = keyWords.random()
        isLoadMore = true
        scrollToTop = true
        fetchData()
    }

    fun fetchData() {
        if (isLoading) return
        if (currentPage > totalPage) {
            _dataStatus.value = DATA_STATUS_NO_MORE
            return
        }
        isLoading = true
        val stringRequest = StringRequest(
            Request.Method.GET,
            getUrl(),
            Response.Listener {
                with(Gson().fromJson(it, Pixabay::class.java)) {
                    totalPage = ceil(totalHits.toDouble() / perPage).toInt()
                    if (isLoadMore) {
                        _gallery.value = this.hits.toList()
                    } else {
                        _gallery.value = arrayListOf(_gallery.value!!, hits.toList()).flatten()
                    }
                }
                _dataStatus.value = DATA_STATUS_LOAD_MORE
                isLoadMore = false
                isLoading = false
                currentPage++
//                _gallery.value = Gson().fromJson(it, Pixabay::class.java).hits.toList()
            },
            Response.ErrorListener {
                _dataStatus.value = NET_WORK_ERROR
                isLoading = false
                Toast.makeText(getApplication(), "加载失败", Toast.LENGTH_SHORT).show()
            }
        )
        VolleySingleton.getInstance(
            getApplication()
        ).requestQueue.add(stringRequest)
    }

    private fun getUrl(): String {
        return "https://pixabay.com/api/?key=14922492-cc46cd3d884b15d6d8a91c039&image_type=photo&pretty=true&q=${currentKey}&per_page=${perPage}&page=${currentPage}"
    }
}